package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.example.config.TencentCosConfig;
import com.example.dto.ArticleDetailDTO;
import com.example.entity.Archives;
import com.example.entity.Article;
import com.example.mapper.ArchivesMapper;
import com.example.mapper.ArticleMapper;
import com.example.service.ArchivesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.service.ArticleService;
import com.example.vo.ArticleDetailVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-04-04
 */
@Lazy
@Slf4j
@Service
public class ArchivesServiceImpl extends ServiceImpl<ArchivesMapper, Archives> implements ArchivesService {
    @Lazy
    @Resource
    private ArticleService articleService;

    @Lazy
    @Resource
    private ArticleMapper articleMapper;

    @Lazy
    @Resource
    private TencentCosConfig tencentCosConfig;
    @Override
    public ArticleDetailVO detail(ArticleDetailDTO articleDetailDTO) {
        Article article = articleService.getById(articleDetailDTO.getArticleId());

        ArticleDetailVO articleDetailVO = new ArticleDetailVO();
        BeanUtil.copyProperties(article, articleDetailVO);

        // 处理封面URL
        String titleImage = article.getTitleImage();
        if (titleImage != null && !titleImage.isEmpty()) {
            // 如果URL不是以http开头，则添加前缀
            if (!titleImage.startsWith("http://") && !titleImage.startsWith("https://")) {
                titleImage = tencentCosConfig.getBaseUrl() + (tencentCosConfig.getBaseUrl().endsWith("/") ? "" : "/") + titleImage;
            }
            articleDetailVO.setCover(titleImage);
            log.info("设置文章封面 - ID: {}, 最终URL: {}", article.getId(), titleImage);
        } else {
            // 不设置默认图片，前端会处理
            articleDetailVO.setCover("");
            log.info("文章无封面 - ID: {}", article.getId());
        }

        articleDetailVO.setSummary(article.getDescription());

        List<Integer> tagIds = articleMapper.getTagIdsByArticleId(articleDetailDTO.getArticleId());
        articleDetailVO.setTagIds(tagIds);

        log.info("文章详情 - ID: {}, 标题: {}", article.getId(), article.getTitle());

        return articleDetailVO;
    }
}
